const TOOLBAR =[
	{content:"添加", icon:"el-icon-document-add",type:"primary"},
	{content:"批量导入", icon:"el-icon-document-copy",},
	{content:"分配", icon:"el-icon-s-custom",},
	//{content:"删除", icon:"el-icon-delete",type:"danger"},
]
const COLUMNS = [
    {prop:"id", label:"客户编号",width:"80"},
	{prop:"createdatetime", label:"添加日期",width:"80"},
	{prop:"founddate", label:"成立日期",width:"80"},
	{prop:"compname", label:"公司名称",width:"150"},
	{prop:"legalperson", label:"法人",width:"80"},
	{prop:"contacter", label:"联系人",width:"80"},
	{prop:"phone", label:"电话",width:"120"},
	{prop:"area", label:"地区",width:"50"},
	{prop:"src", label:"来源",width:"50"},
	{prop:"assignetype", label:"分配方式",width:"80"},
	{prop:"taxtype", label:"税务类型",width:"80"},
	{prop:"status", label:"状态",width:"80"},
	{prop:"memo", label:"备注",width:"100"}	
]

let validate = {
    validatePass: (rule, value, callback) => {
        
    }
};

const customerRules = {
    compname: [
        {required: true, message: '请输入公司名称！', trigger: 'blur'}
    ],
    phone: [
        {required: true, message: '请输入手机号！', trigger: 'blur'}
    ]
};
const importRules = {
    src: [
        {required: true, message: '请选择客户来源', trigger: 'blur'}
    ],
    assignetype: [
        {required: true, message: '请选择分配方式', trigger: 'blur'}
    ],
    deptid: [
        {required: true, message: '请选择部门', trigger: 'blur'}
    ]
};
			
let app = new Vue({
    el: "#app",
    data() {
        return {
			headers: {
				Token: localStorage.getItem('TOKEN'),
				UserID: localStorage.getItem('USERID')
			},
			comptypeoptions:[
				"有限责任公司",
				"有限责任公司(非自然人投资或控股的法人独资)",
				"有限责任公司(自然人独资)",
				"有限责任公司(自然人投资或控股)",
				"有限责任公司(自然人投资或控股的法人独资)",
				"有限责任公司分公司",
				"有限责任公司分公司(非自然人投资或控股的法人独资)"
			],
			taxtypeoptions:[],
        	leftbar_show:true,
			// 添加、编辑标识
			action:"",
			tableHeight:window.innerHeight - 180,
			toolbar:TOOLBAR,
			tablecolums:COLUMNS,
			dialogFormVisible:false,
			dialogAssigneFormVisible:false,
			dialogimportFormVisible :false,
			queryForm:{
				userid: localStorage.getItem('USERID'),
                keyword: "",
				assignetype: [],
                src: [],
                taxtype:[],
				status:"未分配",
				createdatetime:[],
				founddate:[],
				pageNo:1, // 当前页码
				pagesize:100 ,// 每页记录数
				pagesizes:[10,20,50,100,500]
			},
			pagetotal:0, // 总记录数
			pickerOptions: {
			  shortcuts: [{
				text: '最近一周',
				onClick(picker) {
				  const end = new Date()
				  const start = new Date()
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
				  picker.$emit('pick', [start, end])
				}
			  }, {
				text: '最近一个月',
				onClick(picker) {
				  const end = new Date();
				  const start = new Date();
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
				  picker.$emit('pick', [start, end]);
				}
			  }, {
				text: '最近三个月',
				onClick(picker) {
				  const end = new Date();
				  const start = new Date();
				  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
				  picker.$emit('pick', [start, end]);
				}
			  }]
			},
			customerRules, // 数据验证规则
			customerForm: {
				userid: localStorage.getItem('USERID'),
                id: null,
                compname: "",
                legalperson: "",
				contacter:"",
				taxtype:"",
                phone: "",
                address: "",
                area: "",
				comptype:"",
				registeredcapital:"",
				businessscope:"",
				founddate:"",
				createdatetime:"",
				src:"",
				status:"",
				memo:""
            },
			customerFormOrg: {
			},
			trackForm: {
				trackerid:""
			},
			importForm: {
				src:"工商",
				assignetype:"手动",
				deptid:parseInt(localStorage.getItem('DEPTID'))
			},
			// 所有团队人员
			members:[],
			areas:[],
			// 部门列表
			depts:[],
			// 多选
			multipleSelection:[],
			pagedata:[],  // 当前页结果集
			loaded:false,
			//导入加载框
			importloading:null,
			uploadurl:axios.defaults.baseURL + "api/customer/import/" + localStorage.getItem('USERID') + ",",
        }
    },
	methods: {
		// 显示侧边栏
		showLeftBar() {
			if (this.leftbar_show) {
				this.leftbar_show = false
			} else {
				this.leftbar_show = true
			}
		},
		// 表格多选 
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		// 检查数据是否有修改
		checkDataChanged() {
			// 比对数据有无发生变化
			for (let key in this.customerForm) {
				if (this.customerForm[key] != this.customerFormOrg[key]) {
					return true;
				}
			}
			return false;
		},
		beforeAvatarUpload(file) {
			// 显示加载框
			this.importloading = this.$loading(LOAD_STYLE);
			// const isexl = ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"].indexOf(file.type) > -1;
			const isLt5M = file.size / 1024 / 1024 < 20;
			console.log(this.uploadurl + this.importForm.src + ',' + this.importForm.assignetype+ ',' + this.importForm.deptid)
			// if (!isexl) {
			// 	this.$message.error('只能是xls,xlsx格式!');
			// 	// 关闭加载框
			// 	this.importloading.close();
			// 	return false;
			// }
			if (!isLt5M) {
				this.$message.error('上传文件大小不能超过 20MB!');
				// 关闭加载框
				this.importloading.close();
				return false;
			}
			return true;
		},				
		handleAvatarSuccess(res, file, filelist) {
		// 导入完成
			try {
				if (res.code === 200) {
					this.$message.success(res.message);
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			// 关闭加载框
			this.importloading.close();
		},
		// 确认
		async cofirm(){
            this.$refs.customerForm.validate(async valid => {
                if (valid){
					// 显示加载框
					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = null;
						if (this.action=="add") {
							this.customerForm.userid=localStorage.getItem('USERID');
							res = await axios.put('api/customer/add', this.customerForm);
						} else{
							// 编辑
							checkdata = this.checkDataChanged();
							if (checkdata) {
								this.customerForm.recs = checkdata;
								res = await axios.put('api/customer/update', this.customerForm);
							} else {
								res = {code:400,message:"数据未变化"};
							}
						}
						if (res.code === 200) {
							this.query();
							this.dialogFormVisible = false
						}else {
							this.$message.error(res.message);
						}					

					}catch (e) {
						this.$message.error('请求出错！', e.message);
					}
					// 关闭加载框
					loading.close();
                }
            })			
		},
		// 确认分配
		async cofirmAssigne(){
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let ids =[]
				for (let row of this.multipleSelection) {
					ids.push(row.id)
				}
				if (this.trackForm.trackerid == "") {
					this.$message.error("跟踪者不能为空。");
				} else {
					let param = {"trackerid":this.trackForm.trackerid, "ids":ids}
					let res = await axios.put('api/customer/assigne', param);
					if (res.code === 200) {
						this.$message.success(res.message);
						this.query();
						this.dialogAssigneFormVisible = false
					}else {
						this.$message.error(res.message);
					}					
				}

			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			// 关闭加载框
			loading.close();
		},
		start(){
			this.queryForm.pageNo = 1
			this.query()
		},
		// 查询
		async query() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.post('api/customer/query', this.queryForm);
				if (res.code === 200) {
					this.pagedata = res.data;
					this.pagetotal = res.total;
					this.$message.success(res.message);
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},
		toolAction(acName) {
			if (acName == "添加") {
				this.add()
			} else if (acName == "批量导入") {
				this.showImportDialog()
			} else if (acName == "分配") {
				//初始化团队成员列表
				this.initMembers();
				this.assigne();
			} else if (acName == "删除") {
				this.delete()
			}
		},
		selectionChange(selection){
			this.selection = selection
		},
		async showImportDialog() {
			this.dialogimportFormVisible = true;
		},
		// 添加
		add() {
			this.action="add";
			this.dialogFormVisible = true;
            this.customerForm= {
                id: null,
                compname: "",
                legalperson: "",
				contacter:"",
                phone: "",
                address: "",
                area: "",
				comptype:"",
				registeredcapital:"",
				businessscope:"",
				founddate:"",
				createdatetime:"",
				src:"线索",
				status:"正常",
				memo:""
            }
		},
		// 编辑
		edit(index, row) {
			this.action="edit"
			this.index = index;
			this.dialogFormVisible = true;
			this.customerForm = deepCopy(row)
			// 保留原始数据，方便比对
			this.customerFormOrg = deepCopy(row)
		},
		// 分配
		assigne(index, row) {
			if (this.multipleSelection.length > 0) {
				isassigned = false;
				for (let row of this.multipleSelection) {
					if (row.status == "已分配") {
						isassigned = true;
						break;
					}
				}
				if (isassigned) {
					this.$confirm('选择行中有已分配客户，确定要将已分配客户进行再分配吗?', '提示', {
										confirmButtonText: '确定',
										cancelButtonText: '取消',
										type: 'warning'
					}).then(async () => {
						this.dialogAssigneFormVisible = true;
					}).catch((e) => {
						return;
					});
				} else {
					this.dialogAssigneFormVisible = true;
				}
			} else {
				this.$message.error('请选择数据行！');
			}
		},
		async delete() {
			try {
				ids =[]
				for (let row of this.multipleSelection) {
					ids.push(row.id)
				}
				if (ids.length > 0) {
					this.$confirm('此操作将永久删除选定的行, 是否继续?', '提示', {
					                confirmButtonText: '确定',
					                cancelButtonText: '取消',
					                type: 'warning'
					            }).then(async () => {
									let res = await axios.put('api/customer/delete', ids);
									if (res.code === 200) {
										this.query();
										this.$message.success(res.message);
									}else {
										this.$message.error(res.message);
									}	
					            }).catch((e) => {
					                if (e.message) this.Msg('error', e.message);
					            });
				} else {
					this.$message.error('请先选择要删除的数据行！');
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
		},
		// 设定表格当前页
		handleCurrentPageChange (selectedPageNo) {
		  this.queryForm.pageNo = selectedPageNo
		  // 加载数据页
		  this.query()
		},
		//设定每页记录数
		handleSizeChange(val) {
			this.queryForm.pagesize = val
		  // 加载数据页
		  this.query()
	    },
		// 初始化团队成员列表
		async initMembers() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/team/member/' + localStorage.getItem('USERID'));
				if (res.code === 200) {
					this.members = res.data;
					if (this.members.length > 0) {
						this.trackForm.trackerid = this.members[0].id;
					}
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},
		// 打开添加区域对话框
		addAreaDailogOpen() {
			this.$prompt('请输入区域名称', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			  inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
			  inputErrorMessage: '区域名称不能为空'
			}).then(({ value }) => {
				this.areaSubmit(value);
			}).catch(() => {
				this.$message.error('请求出错！', value);
			});
		},
		async areaSubmit(value) {
			res = await axios.put('api/area/add/'+ value);
			if (res.code === 200) {
				this.initAreas();
			}else {
				this.$message.error(res.message);
			}
		},
		async initAreas() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/area/list');
				if (res.code === 200) {
					this.areas = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},
		// 取得所有部门列表
		async getAllDept() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/alldept');
				if (res.code === 200) {
					this.depts = res.data;
				}else {
					this.$message.error(res.message);
				}
			}catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			
			// 关闭加载框
			loading.close();
		},

		async getTaxTyps() {
		// 取得所有税务类型
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/customer/gettaxtyps');
				if (res.code === 200) {
					this.taxtypeoptions = res.data;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('取得税务类型请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		}
		
	},


	async mounted() {
		// 自动调整表格高度
		window.onresize = () => {
		  return (() => {
			this.tableHeight = window.innerHeight - 180
		  })()
		},
		// 初始化区域列表
		this.initAreas();
		// 初始化部门列表
		this.getAllDept()
		//  取得所有税务类型
		this.getTaxTyps()
	
	}

});	